//
//  PushWebViewController.swift
//  Lottery
//
//  Created by 薛永伟 on 2018/12/25.
//  Copyright © 2018年 薛永伟. All rights reserved.
//

import UIKit
import WebKit

class PushWebViewController: UIViewController {
    
    lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        config.allowsPictureInPictureMediaPlayback = false
        config.allowsAirPlayForMediaPlayback = false
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        
        if let jsPath = Bundle.main.path(forResource: "JSBridge", ofType: "js"){
            config.userContentController = WKUserContentController()
            var source = try! NSString(contentsOfFile: jsPath, encoding: String.Encoding.utf8.rawValue) as String
            let userScript = WKUserScript.init(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
            config.userContentController.addUserScript(userScript)
            config.userContentController.add(self, name: "OOFJS")
        }
        
        let webview = WKWebView.init(frame: CGRect.zero, configuration: config)
        webview.scrollView.bounces = false
        webview.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        webview.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
        webview.uiDelegate = self
        webview.allowsBackForwardNavigationGestures = true
        return webview
    }()
    
    lazy var progressView: UIProgressView = {
        let view = UIProgressView.init(progressViewStyle: .bar)
        view.progressTintColor = UIColor.init(rgb: 0x999999)
        return view
    }()
    
    var loadUrl:URL
    
    var popWhenClickBack:Bool = false
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        webView.removeObserver(self, forKeyPath: "title")
    }
    
    init(url:URL) {
        
        self.loadUrl = url
        
        super.init(nibName: nil, bundle: nil)
        
        self.hidesBottomBarWhenPushed = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        self.view.addSubview(progressView)
        progressView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        let request = URLRequest.init(url: self.loadUrl)
        self.webView.load(request)
        
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }
    
    override func observeValue(forKeyPath keyPath: String?,
                               of object: Any?,
                               change: [NSKeyValueChangeKey : Any]?,
                               context: UnsafeMutableRawPointer?) {
        
        if keyPath == "estimatedProgress" {//进度
            self.progressView.progress = Float(self.webView.estimatedProgress);
            self.progressView.isHidden = self.progressView.progress > 0.99
        }else if keyPath == "title"{
            self.title = webView.title
        }
    }
    
}

//MARK: - --------------WKNavigationDelegate--------------
extension PushWebViewController:WKNavigationDelegate {
    
    /// 是否允许请求
    func webView(_ webView: WKWebView,
                 decidePolicyFor navigationAction: WKNavigationAction,
                 decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        decisionHandler(.allow)
        
    }
    /// 是否允许响应
    func webView(_ webView: WKWebView,
                 decidePolicyFor navigationResponse: WKNavigationResponse,
                 decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        decisionHandler(.allow)
    }
    
    /// 授权
    func webView(_ webView: WKWebView,
                 didReceive challenge: URLAuthenticationChallenge,
                 completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        
        if let trust = challenge.protectionSpace.serverTrust {
            completionHandler(.useCredential, URLCredential(trust: trust))
        } else {
            completionHandler(.performDefaultHandling, nil)
        }
    }
    
    /// main frame的导航开始请求
    func webView(_ webView: WKWebView,
                 didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    /// 当main frame接收到服务重定向时调用
    func webView(_ webView: WKWebView,
                 didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    /// 当main frame开始加载数据失败时，会回调
    func webView(_ webView: WKWebView,
                 didFailProvisionalNavigation navigation: WKNavigation!,
                 withError error: Error) {
        
    }
    
    /// 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
        YRLog("didCommit navigation", type: .info)
    }
    /// 当main frame导航完成时，会回调
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        YRLog("didFinish navigation", type: .info)
    }
    /// 当main frame最后下载数据失败时，会回调
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
    }
    /// 当web content处理完成时，会回调
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        
        YRLog("webViewWebContentProcessDidTerminate", type: .info)
    }
    
}

//MARK: - --------------WKUIDelegate--------------
extension PushWebViewController:WKUIDelegate{
    
    /// 要打开新的网页
    func webView(_ webView: WKWebView,
                 createWebViewWith configuration: WKWebViewConfiguration,
                 for navigationAction: WKNavigationAction,
                 windowFeatures: WKWindowFeatures) -> WKWebView? {
        
        // 还是用我当前的webview
        return self.webView
    }
    
    /// 要关闭当前的网页
    func webViewDidClose(_ webView: WKWebView) {
        
        let alv = UIAlertController.init(title: "要关闭网页？", message: nil, preferredStyle: .alert)
        let cancle = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
        }
        let OK = UIAlertAction.init(title: "确定", style: .default) { (action) in
            self.navigationController?.popViewController(animated: true)
        }
        alv.addAction(cancle)
        alv.addAction(OK)
        self.present(alv, animated: true, completion: nil)
    }
    
    /// 网页提示
    func webView(_ webView: WKWebView,
                 runJavaScriptAlertPanelWithMessage message: String,
                 initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping () -> Void) {
        
        let alv = UIAlertController.init(title: message, message: nil, preferredStyle: .alert)
        let OK = UIAlertAction.init(title: "好的", style: .default) { (action) in
            completionHandler()
        }
        alv.addAction(OK)
        self.present(alv, animated: true, completion: nil)
    }
    
    /// 网页询问
    func webView(_ webView: WKWebView,
                 runJavaScriptConfirmPanelWithMessage message: String,
                 initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (Bool) -> Void) {
        
        let alv = UIAlertController.init(title: message, message: nil, preferredStyle: .alert)
        let cancle = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
            completionHandler(false)
        }
        let OK = UIAlertAction.init(title: "确定", style: .default) { (action) in
            completionHandler(true)
        }
        alv.addAction(cancle)
        alv.addAction(OK)
        self.present(alv, animated: true, completion: nil)
    }
    
    /// 网页输入
    func webView(_ webView: WKWebView,
                 runJavaScriptTextInputPanelWithPrompt prompt: String,
                 defaultText: String?,
                 initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (String?) -> Void) {
        
        let alv = UIAlertController.init(title: prompt, message: nil, preferredStyle: .alert)
        alv.addTextField { (tf) in
            tf.placeholder = "请输入"
        }
        
        let cancle = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
            let text = alv.textFields?.first?.text
            completionHandler(text)
        }
        let OK = UIAlertAction.init(title: "确定", style: .default) { (action) in
            completionHandler(defaultText)
        }
        alv.addAction(cancle)
        alv.addAction(OK)
        self.present(alv, animated: true, completion: nil)
    }
}

/// 导航操作
extension PushWebViewController:BaseNavigationProtocol {
    
    func stopClickBackToPop() -> Bool {
        
        if popWhenClickBack {
            return false
        }
        
        if self.webView.canGoBack {
            self.webView.goBack()
            return true
        }else{
            return false
        }
    }
}

extension PushWebViewController :WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController,
                               didReceive message: WKScriptMessage) {
        
        if message.name == "OOFJS" {
            // 处理JS主动调用的方法
            guard let dic = message.body as? [String:Any],let fun = dic["fun"] as? String else {
                return
            }
            
            if let arg = dic["arg"] as? [String:String]{
                if fun == "jump2Browser",
                    let url = arg["url"]{
                    
                    YRLog(url)
                    openInSafari(urlString: url)
                }
                
            }
        }
    }
    
    
    
}

extension PushWebViewController {
    
    func openInSafari(urlString:String){
        
        if let url = URL.init(string: urlString.urlQuryEncode){
            UIApplication.shared.openURL(url)
        }
        
    }
}



